package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private JedisPool jedisPool;


    //获取当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername() throws Exception {
        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, user.getUsername());
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    //修改密码
    @RequestMapping("/editPwd")
    @PreAuthorize("hasAnyAuthority('USER_EDIT')")//调用此方法需要使用编辑用户的权限
    public Result editPwd(@RequestBody Map map) {
        try{
            String username = (String) this.getUsername().getData();
            Boolean flag =  userService.editPwd(username,map);
            if(flag) {
                return new Result(true, "密码修改成功！");
            }else {
                return new Result(false,"修改密码失败，请重新输入！");
            }

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"出现网络异常，请再次尝试！");
        }
    }

    //查找用户信息
    @RequestMapping("/findPage")
    @PreAuthorize("hasAnyAuthority('USER_QUERY')")//调用此方法需要查询用户的权限
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        PageResult pageResult=null;
        try {
            pageResult= userService.findPage(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;

    }

    //添加新用户
    @RequestMapping("/add")
    @PreAuthorize("hasAnyAuthority('USER_ADD')")//调用此方法需要使用新增用户的权限
    public Result add(@RequestBody com.itheima.pojo.User user, Integer[] roleIds) {
        try {

            userService.add(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS);
    }


    //通过用户id查找关联的角色id
    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer userId) {

        try{
            List<Integer> roleIds = userService.findRoleIdsByUserId(userId);
            return new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLE_FAIL);
        }
    }

    //根据用户id查询用户信息
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('USER_QUERY')")//调用此方法需要使用查询用户的权限
    public Result findById(Integer userId) {

        try{
            com.itheima.pojo.User user = userService.findById(userId);
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    //通过用户基本信息和角色ID更新用户信息
    @RequestMapping("/edit")
    @PreAuthorize("hasAnyAuthority('USER_EDIT')")//调用此方法需要编辑用户的权限
    public Result edit(@RequestBody com.itheima.pojo.User user, Integer[] roleIds) {
        try {
            userService.edit(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL+","+e.getMessage());
        }
        return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
    }

    //根据id删除
    @RequestMapping("/delete")
    @PreAuthorize("hasAnyAuthority('USER_DELETE')")//调用此方法需要删除用户的权限
    public Result delete(Integer id) {

        try{
            userService.deleteById(id);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL+","+e.getMessage());
        }
    }


    @RequestMapping("/findAllMenu")
    public Result findAllMenu(String username) {
        try{
            List<Menu> list = userService.findAllMenu(username);
            return new Result(true,MessageConstant.QUERY_MENU_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    @RequestMapping("/findByTelephone")
    @PreAuthorize("hasAnyAuthority('USER_QUERY')")//调用此方法要求当前用户必须具有查询用户权限
    public Result findByTelephone(String telephone) {
        try{
            com.itheima.pojo.User user = userService.findByTelephone(telephone);
            if (user == null) {
                return new Result(false, "您还不是该系统用户，请联系管理员！");
            }
            return new Result(true,"查找成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "发生网络波动，请重新操作！");
        }
    }

    @RequestMapping("/editPassWord")
    @PreAuthorize("hasAnyAuthority('USER_EDIT')")//调用此方法需要编辑用户的权限
    public Result editPassWord(@RequestBody Map map){
        String telephone =(String) map.get("telephone");
        String code =(String)map.get("code");
        String password =(String) map.get("newPwd");

        Jedis resource = jedisPool.getResource();
        //得到前台传过来的验证码
        //获取缓存库中的验证码
        //1.从Redis中获取保存的验证码
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (validateCodeInRedis==null ||  !validateCodeInRedis.equals(code)){
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //验证码验证通过,用户信息匹配成功
        //调用修改用户的方法就行了

        userService.editPwdByTelandNewPwd(telephone,password);

        return  new Result(true,"修改密码成功");
    }

    //修改权限状态
    @RequestMapping("/changeStatus")
    public Result changeStatus(@RequestBody Map<String,Object> map) {

        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userService.changeStatus(map,user.getUsername());
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL+","+e.getMessage());
        }
    }
}
